package com.baykalcakici.cafepicker;

import java.util.List;
import java.util.Map;

import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;


import com.baykalcakici.cafepicker.picker.CafeHistoryItem;
import com.baykalcakici.cafepicker.tasks.LoginTask;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.widget.SimpleAdapter;

/**
 * History tab. Reoresents available cafes in a list view.
 */
public class Stats extends ListActivity {
  private List<CafeHistoryItem> cafeItems;
  private static DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("MM-dd-yyyy E HH:mm:ss");

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.stats);
  }

  @Override
  protected void onResume() {
    super.onResume();
    displayCafeNames();
  }

  private void displayCafeNames() {
    if (cafeItems != null && cafeItems.isEmpty()) {
      ProgressDialog dialog =
          ProgressDialog.show(Stats.this, "", "Re-initializing. Please wait...", true);
      LoginTask loginTask = new LoginTask(dialog, Stats.this);
      loginTask.execute();
    }

    if (cafeItems == null || cafeItems.isEmpty()) {
      cafeItems = Main.cafePicker.getPreviouslyVisitedCafes();
      if (!cafeItems.isEmpty()) {
        List<Map<String, String>> data = Lists.newArrayList();
        for (CafeHistoryItem item : cafeItems) {
          Map<String, String> map = Maps.newHashMap();
          map.put("name", item.name);
          map.put("dateTime", item.dateTime.toString(FORMATTER));
          data.add(map);
        }

        String[] from = {"name", "dateTime"};
        int[] to = {android.R.id.text1, android.R.id.text2};

        setListAdapter(new SimpleAdapter(this, data, android.R.layout.simple_list_item_2,
            from, to));
      }
    }
  }
}
